import React, { Component } from 'react'
import { View, Text, FlatList, Image, Alert } from 'react-native'
import styles from './List_style'
import { get } from '@/src/utils/http'

interface Props {
  route?: any,
  navigation?: any
}
interface State {
  refresh: boolean,
  datalist: any,
  page: number
}

export default class List extends Component<Props, State> {
  state = {
    limit: 10,
    page: 1,
    datalist: [],
    refresh: false
  }

  componentDidMount() {
    this.props.navigation.setOptions({
      title: this.props.route.params.title
    })
    this._loadData()
  }

  async _loadData() {
    let url = `http://192.168.2.1:8088/list?_limit=${this.state.limit}&_page=${this.state.page}`;//&q=排骨
    let result = await get(url)
    this.setState({
      datalist: this.state.datalist.concat(result),
      refresh: false
    })
    console.log('List:', result)
  }

  _renderItem({ item }) {
    let { img, name, burdens, all_click, favorites } = item;
    // console.log('img:',item)
    return (
      <View style={styles.listWrap}>
        <View style={styles.imgWrap}>
          <Image style={styles.image} source={{ uri: img }}></Image>
        </View>

        <View style={styles.descWrap}>
          <Text style={styles.title}>{name}</Text>
          <Text style={styles.subtitle} numberOfLines={1} ellipsizeMode="tail">{burdens}</Text>
          <Text style={styles.desc}>{all_click} {favorites}</Text>
        </View>

      </View>
    )
  }

  _handleRefresh() {
    this.setState({
      refresh: true,
      page: 0,
      datalist: []
    })
    this._loadData();
  }

  _handleEndReach = () => {
    
    let cur = this.state.datalist.length / this.state.limit
    console.log('end',this.state.page,cur)
    if (this.state.page === cur) {
      this.setState((state) => {
        return {
          page: state.page + 1
        }
      }, () => {
        this._loadData()
      })
    } else {
      Alert.alert('已经到达最后了')
    }
  }

  render() {
    return (
      <FlatList
        renderItem={this._renderItem.bind(this)}
        data={this.state.datalist}
        onRefresh={() => {
          this._handleRefresh()
        }}
        keyExtractor={(item: object, index: number)=>index+''}
        refreshing={this.state.refresh}
        onEndReached={this._handleEndReach}
        onEndReachedThreshold={0.2}
        ItemSeparatorComponent={()=>{
          return (
            <View style={styles.itemSeparator}>
            </View>
          )
        }}
      >
        <Text>list</Text>
      </FlatList>
    )
  }
}
